from fastapi import APIRouter, Depends, Request
from sqlalchemy.ext.asyncio import AsyncSession

from config.enums import BusinessType
from config.get_db import get_db
from module_admin.annotation.log_annotation import Log
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from module_admin.service.login_service import LoginService
from module_stock.entity.vo.info_vo import InfoPageQueryModel
from module_stock.service.info_service import InfoService
from utils.log_util import logger
from utils.page_util import PageResponseModel
from utils.response_util import ResponseUtil

infoController = APIRouter(prefix='/stock/info', dependencies=[Depends(LoginService.get_current_user)])


@infoController.get(
    '/list', response_model=PageResponseModel, dependencies=[Depends(CheckUserInterfaceAuth('stock:info:list'))]
)
async def get_stock_info_list(
        request: Request,
        info_page_query: InfoPageQueryModel = Depends(InfoPageQueryModel.as_query),
        query_db: AsyncSession = Depends(get_db),
):
    # 获取分页数据
    info_page_query_result = await InfoService.get_info_list_services(query_db, info_page_query, is_page=True)
    logger.info('获取成功')

    return ResponseUtil.success(model_content=info_page_query_result)


@infoController.post('/sync/full', dependencies=[Depends(CheckUserInterfaceAuth('stock:info:edit'))])
@Log(title='全量同步股票信息', business_type=BusinessType.INSERT)
async def sync_full_stock_info(request: Request, query_db: AsyncSession = Depends(get_db)):
    """
    全量同步股票信息
    """
    # 调用service中的同步股票数据方法
    sync_result = await InfoService.sync_full_stock_info_services(query_db)
    logger.info(sync_result.message)

    return ResponseUtil.success(model_content=sync_result)


@infoController.post('/sync/incremental', dependencies=[Depends(CheckUserInterfaceAuth('stock:info:edit'))])
@Log(title='增量同步股票信息', business_type=BusinessType.INSERT)
async def sync_incremental_stock_info(request: Request, query_db: AsyncSession = Depends(get_db)):
    """
    增量同步股票信息
    """
    # 调用service中的增量同步股票数据方法
    sync_result = await InfoService.sync_incremental_stock_info_services(query_db)
    logger.info(sync_result.message)

    return ResponseUtil.success(model_content=sync_result)


@infoController.get('/check/{stock_code}')
async def check_stock_exists(
        request: Request,
        stock_code: str,
        query_db: AsyncSession = Depends(get_db)
):
    """
    检查股票代码是否存在
    """
    from utils.stock_util import add_stock_suffix

    try:
        # 为股票代码添加交易所后缀
        suffixed_stock_code = add_stock_suffix(stock_code)
    except ValueError as e:
        # 添加后缀失败，返回不存在
        return ResponseUtil.error(msg=f"股票代码 {stock_code} 格式错误")

    # 调用service中的方法检查股票是否存在
    stock_exists = await InfoService.check_stock_exists_services(query_db, suffixed_stock_code)

    if stock_exists:
        return ResponseUtil.success(msg=f"股票代码 {stock_code} 正确")
    else:
        return ResponseUtil.error(msg=f"股票代码 {stock_code} 查询不到股票")


@infoController.post('/stock_tick')
async def get_stock_tick_data(
        request: Request,
        stock_codes: str,
):
    """
    根据股票代码列表获取股票tick数据
    """
    try:
        from xtquant import xtdata
        # 使用xtdata.get_full_tick方法获取股票tick数据
        tick_data = xtdata.get_full_tick(stock_codes.split(','))
        logger.info(f'获取股票tick数据成功，共{len(tick_data)}条数据')
        return ResponseUtil.success(data=tick_data)
    except Exception as e:
        logger.error(f'获取股票tick数据失败: {e}')
        return ResponseUtil.error(msg=f'获取股票tick数据失败: {str(e)}')
